package com.ks.sgms.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.ks.sgms.util.DbHelper;


public class AdminDao {
	
	public boolean login(String user_name, String password) {
		Connection conn = DbHelper.getConnection();
		PreparedStatement pst = null;
		ResultSet rst = null;
		boolean checker = false;
		String sql = "SELECT * FROM admin WHERE user_name=? AND password=?";
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, user_name);
			pst.setString(2, password);
			rst = pst.executeQuery();
			if (rst.next()) {
				checker = true;
			} else {
				checker = false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DbHelper.close(pst, rst);
		return checker;
	}

	public boolean register(String user_name, String password) {
		Connection conn = DbHelper.getConnection();
		PreparedStatement pst = null;
		boolean rChecker = false;
		String sql = "INSERT INTO admin(user_name,password) VALUES(?,?)";
		if (!this.registerCheck(user_name)) {
			try {
				pst = conn.prepareStatement(sql);
				pst.setString(1, user_name);
				pst.setString(2, password);
				pst.executeUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			}
			rChecker = true;
		} else {
			rChecker = false;
		}
		DbHelper.close(pst, null);
		return rChecker;
	}
	
	/**
	 * 	判断名为user_name的用户是否已在表中存在，存在则返回false
	 * @param user_name
	 * @return
	 */
	public boolean registerCheck(String user_name) {
		Connection conn = DbHelper.getConnection();
		PreparedStatement pst = null;
		ResultSet rst = null;
		boolean checker = false;
		String sql = "SELECT * FROM admin WHERE user_name=?";
		try {
			pst = conn.prepareStatement(sql);
			pst.setString(1, user_name);
			rst = pst.executeQuery();
			if (rst.next()) {
				DbHelper.close(pst, rst);
				checker = true;
			} else {
				DbHelper.close(pst, rst);
				checker = false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return checker;
	}
}
